#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Last Update: 2010/10/29 22:12:17

'''docstring
'''

__revision__ = '0.1'
__author__ = 'lxd'
import win32gui
import win32con
import win32ui
import binascii
import tools

class Window():
    def __init__(self):
        pos = win32gui.GetCursorPos()
        self.hwnd = win32gui.WindowFromPoint(pos)

    def active(self):
        win32gui.SendMessage(self.hwnd, win32con.WM_ACTIVATE, win32con.WA_ACTIVE, 0)

    def getRect(self):
        return win32gui.GetWindowRect(self.hwnd)

    def getClassName(self):
        return win32gui.GetClassName(self.hwnd)
    
    def getWindowText(self):
        #经常为空
        return win32gui.GetWindowText(self.hwnd)

    def getColor(self,x,y):
        '''
        get color of one point
        '''
        return self.__getColors(x,y,1,1)[:-2]

    def isColor(self,x,y,color):
        if self.getColor(x,y) == color:
            return True
        else:
            return False

    def getColors(self,left,top,right,bottom):
        '''
        get colors in regions
        '''
        width = right-left+1
        height = bottom-top+1
        bits = self.__getColors(left,top,width,height)
        return tools.createBitsList(bits,width,height)

    def __getColors(self,x,y,width,height):
        #从源图像的(x,y)位置处开始获得(width,height)大小区域的颜色：
        hdc_screen=win32gui.GetDC(self.hwnd)
        hmem_dc = win32gui.CreateCompatibleDC(hdc_screen)
        h_bitmap = win32gui.CreateCompatibleBitmap(hdc_screen, width, height)
        h_old_bitmap = win32gui.SelectObject(hmem_dc, h_bitmap)
        win32gui.BitBlt(hmem_dc, 0, 0, width, height, hdc_screen, x, y, win32con.SRCCOPY)  
        win32gui.DeleteDC(hmem_dc) 
        win32gui.ReleaseDC(self.hwnd,hdc_screen)

        x = win32ui.CreateBitmapFromHandle(h_bitmap) 
        bits = x.GetBitmapBits(True)
        return binascii.hexlify(bits).upper()

    def findRegionColor(self,left,top,right,bottom,color):
        '''从左到右，从上到下找色
        '''
        colors = self.getColors(left,top,right,bottom)
        return tools.findRegionFlag(colors,color)

    def findCenterColor(self,left,top,right,bottom,color):
        '''从中心到外围找色
        '''
        colors = self.getColors(left,top,right,bottom)
        return tools.findCenterFlag(colors,color)

if __name__ == '__main__':
    w = Window()
    print w.hwnd
    print w.getRect()
    print w.getClassName()
    print w.getWindowText()
    x,y = 183,25
    print w.getColor(x,y)
    print w.getColors(5,5,10,10)
    print w.findCenterColor(0,0,1280,800,'8CE6F0')
    
